import React, { useState, useRef, useEffect } from 'react'
import './Message.css'
import useWeb from '../../useWeb'
const Message = () => {
    const { sendMsg, data } = useWeb('ws://localhost:8080')
    // ref
    const mtinput = useRef<HTMLInputElement>(null)

    // const ws = new WebSocket('ws://localhost:8080');
    const send = () => {
        // ws.send((mtinput.current! as HTMLInputElement).value);
        sendMsg((mtinput.current! as HTMLInputElement).value);
        // 清除输入框
        (mtinput.current! as HTMLInputElement).value = ''
    }

    // 所有信息组成数组
    const [lits, setLits] = useState<any>([])
    useEffect(() => {
        // 添加
        lits.push(data)
        // 刷新
        setLits([...lits])
    }, [data])

    return (
        <div className='box'>
            <div className='message-box'>
                {
                    lits.map((item: any, index: number) => {
                        return <div key={index} style={{ textAlign: 'right' }} >{item} :小帅</div>
                    })
                }
            </div>
            <div className='send-box'>
                <input ref={mtinput} type="text" />
                <button onClick={send}>发送</button>
            </div>
        </div>
    )
}

export default Message
